# include "led.h"
# include "tim.h"

void led_on(LED_TYPE type)
{
	if (type==RED_LED){
       TIM1->CCR1=0;		
		//HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8,GPIO_PIN_RESET);
	}
    else if (type==GREEN_LED){
		HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_RESET);
	}
	
}

	
	void led_off(LED_TYPE type)
{
	if (type == RED_LED){
		HAL_GPIO_WritePin(GPIOA ,GPIO_PIN_8,GPIO_PIN_SET);
	}
	else if(type == GREEN_LED){
		HAL_GPIO_WritePin(GPIOD ,GPIO_Pin_2,GPIO_PIN_SET);
	}
}
	void  led_blink(LED_TYPE type,uint32_ millisecond,uint32_t times)
	{
		int i;
		for(i=0; i< times*2; i++)
		{
			if(type == RED_LED)
			{
				HAL_GPIO_Togglepin(GPIOA,GPIO_PIN_8);
			}
			else if(type == GREEN_LED){
				HAL_GPIO_Togglepin(GPIOD,GPIO_PIN_2);
			}
			HAL_Delay(millisecond);
		}
	}
	
	void led_breathing(LED_TYPE type,uint32_ millisecond,uint32_t times)
	{
		int vector = 1;
		int ccr = 0;
		int period = 1000;
		int delay = (int)(((float)period / (millisecond/2)) *20);

		if (type != RED_LED) return ;
		
		while (1)
		{
			if (vector)ccr +=delay;
			else ccr -=delay;

			if(ccr>1000) vector=0;
			if(ccr<=0) {
				vector=1;
				times --;
			}

			TIM1->CCR1 = ccr;

			HAL_Delay(20);
		}
	}
	
	LED led = {
		.on = led_on ,
		.off = led_off ,
		.blink = led_blink,
		.breathing = led_breathing,
	};

	


 HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_1);

	led.on(RED_LED);
	led.on(GREEN_LED);
HAL_Delay(1000);

  led.off(RED_LED);
	led.off(GREEN_LED);
  HAL_Delay(1000);

	led.blink(RED_LED,500,1);
	led.blink(GREEN_LED,500,1);

 led.breathing(RED_LED,500,1);
	led.breathing(GREEN_LED,500,1);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  HAL_TIM_Base_Start_IT(&htim2);
  while (1)
  {
    /* USER CODE END WHILE */
printf("Hello,IoTProject\r\n");
HAL_Delay(1000);
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

